# MainWindow.py

"""
    Displays the main UGI window
"""

import sys
import argparse

from PySide import QtGui
from PySide import QtCore

import app.Physical as Physical             # physical measurements and accuracy
from   app.Physical import tstamp as now_t  # kludge for python 3.2 -- would like 3.3
import app.PassData as PassData             # data about race runs
import app.RaceTrack as RaceTrack           # works with various race tracks
import app.Receiver as  Receiver            # wrapper for the processing thread
import app.Config as Config                 # arg / config file getter/setter
import app.FakeCar as FakeCar               # creates fake pass

import gui.RacePanel as RacePanel           # Race panel for main window
import gui.ResultsPanel as ResultsPanel     # Results panel for main window
import gui.ChartsPanel as ChartsPanel       # Charts panel for main window

##TODO an application icon would be nice
##TODO implement a racetrack chooser

class RocketWheels(QtGui.QMainWindow):
    raceResult = QtCore.Signal(str, object)

    def __init__(self):
        """Application initialization"""

        super(RocketWheels, self).__init__()

        # Set up some global references
        self.config = Config.Get()
        if(self.config.debug):
            print("Config: ", self.config)

##TODO is this necessary? or is the one in RacePanel the proper one?
        self.raceResult.connect(self.getRaceResult)

        # Display the main UI window
        self.buildUI()

    def buildUI(self):
        """Build main UI window"""

        # Exit command, File/Exit
        self.exitAction = QtGui.QAction(QtGui.QIcon('images/Exit_Button.png'), '&Exit', self)
        self.exitAction.setShortcut('Ctrl+Q')
        self.exitAction.setStatusTip('Exit application')
        self.exitAction.triggered.connect(self.close)

        # New Database command, File/New Database
        newDatabase = QtGui.QAction(QtGui.QIcon('images/New_Database_Button.png'), '&New Database', self)
        newDatabase.setShortcut('Ctrl+N')
        newDatabase.setStatusTip('Create new database')
        newDatabase.triggered.connect(self.createNewDatabase)

        # Open Database command, File/Open Database
        openDatabase = QtGui.QAction(QtGui.QIcon('images/Open_Database_Button.png'), '&Open Database', self)
        openDatabase.setShortcut('Ctrl+O')
        openDatabase.setStatusTip('Open existing database')
        openDatabase.triggered.connect(self.openExistingDatabase)

        # Settings command, Edit/Settings
        editSettings = QtGui.QAction(QtGui.QIcon('images/Settings_Button.png'), 'Se&ttings', self)
        editSettings.setShortcut('Ctrl+T')
        editSettings.setStatusTip('Edit settings')
        editSettings.triggered.connect(self.settingsMenu)

        # Add Car command, Tools/Add Car
        self.addCar = QtGui.QAction(QtGui.QIcon('images/Add_Car_Button.png'), '&Add Car', self)
        self.addCar.setShortcut('Ctrl+A')
        self.addCar.setStatusTip('Add new car')
        self.addCar.triggered.connect(self.addNewCar)

        # Add Driver command, Tools/Add Driver
        self.addDriver = QtGui.QAction(QtGui.QIcon('images/Add_Driver_Button.png'), 'Add &Driver', self)
        self.addDriver.setShortcut('Ctrl+D')
        self.addDriver.setStatusTip('Add new driver')
        self.addDriver.triggered.connect(self.addNewDriver)

        # Start Race command, Tools/Start/Stop
        self.startRace = QtGui.QAction(QtGui.QIcon('images/Start_Button.png'), 'Start Race', self)
        self.startRace.setStatusTip('Start new race')
        self.startRace.triggered.connect(self.startNewRace)

        # Stop Race command
        self.stopRace = QtGui.QAction(QtGui.QIcon('images/Stop_Button.png'), 'Stop Race', self)
        self.stopRace.setStatusTip('Stop current race')
        self.stopRace.triggered.connect(self.stopCurrentRace)

        # Race command
        self.race = QtGui.QAction(QtGui.QIcon('images/Race_Button.png'), '&Race', self)
        self.race.setShortcut('Ctrl+R')
        self.race.setStatusTip('Switch to race mode')
        self.race.triggered.connect(self.raceMode)

        # Results command
        self.results = QtGui.QAction(QtGui.QIcon('images/Results_Button.png'), 'Res&ults', self)
        self.results.setShortcut('Ctrl+U')
        self.results.setStatusTip('Switch to results mode')
        self.results.triggered.connect(self.resultsMode)

        # Charts command
        self.charts = QtGui.QAction(QtGui.QIcon('images/Charts_Button.png'), 'C&harts', self)
        self.charts.setShortcut('Ctrl+H')
        self.charts.setStatusTip('Switch to charts mode')
        self.charts.triggered.connect(self.chartsMode)

        # Add a status bar
        self.statusBar()

        # Add a menu bar
        menubar = self.menuBar()

        # Add menus to menubar
        fileMenu = menubar.addMenu('&File')
        editMenu = menubar.addMenu('&Edit')
        toolMenu = menubar.addMenu('&Tools')

        # File Menu
        fileMenu.addAction(newDatabase)
        fileMenu.addAction(openDatabase)
        fileMenu.addSeparator()
        fileMenu.addAction(self.exitAction)

        # Edit Menu
        editMenu.addAction(editSettings)

        # Tools menu
        toolMenu.addAction(self.addCar)
        toolMenu.addAction(self.addDriver)
        toolMenu.addAction(self.startRace)
        toolMenu.addAction(self.stopRace)
        toolMenu.addSeparator()
        toolMenu.addAction(self.race)
        toolMenu.addAction(self.results)
        toolMenu.addAction(self.charts)

        # Add a toolbar
        self.toolbar = self.addToolBar('Exit')
        self.toolbar.setIconSize(QtCore.QSize(60, 60))

        # Add toobar items
        self.toolbar.addAction(self.addCar)
        self.toolbar.addAction(self.addDriver)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.race)
        self.toolbar.addAction(self.results)
        self.toolbar.addAction(self.charts)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.startRace)
        self.toolbar.addAction(self.stopRace)

        toolbarStretch = QtGui.QWidget()
        toolbarStretch.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)
        self.toolbar.addWidget(toolbarStretch)

        self.toolbar.addAction(self.exitAction)

        self.stopRace.setVisible(False)

        self.racePanel = RacePanel.RacePanel(self)
        self.resultsPanel = ResultsPanel.ResultsPanel()
        self.chartsPanel = ChartsPanel.ChartsPanel()

        self.mainStack = QtGui.QStackedWidget()

        self.mainStack.addWidget(self.racePanel)
        self.mainStack.addWidget(self.resultsPanel)
        self.mainStack.addWidget(self.chartsPanel)

        self.setCentralWidget(self.mainStack)

        # Set the title bar value and display the window
        self.setWindowTitle('RocketWheels')

        # Set window size and position (left, top, width, height)
        # self.setGeometry(800, 20, 800, 800)
        # self.show()
        self.showMaximized()

    """call creation of new database"""
    def createNewDatabase(self):
        self.racePanel.appendOutput("New database created")

    """call open of existing database"""
    def openExistingDatabase(self):
        self.racePanel.appendOutput("Existing database opened")

    """call Settings command"""
    def settingsMenu(self):
        self.racePanel.appendOutput("Open settings menu")

    """call Add New Car"""
    def addNewCar(self):
        self.racePanel.appendOutput("Add new car")

    def addNewDriver(self):
        self.racePanel.appendOutput("Add new driver")

    def startNewRace(self):
        self.startRace.setVisible(False)
        self.stopRace.setVisible(True)

        self.racePanel.clearOutput()
        self.racePanel.appendOutput("You started a new race")
        race_track = RaceTrack.RaceTrack( now_t(), 'dev_racetrack' )
        pass_data = FakeCar.create_fake_car(race_track)
        #pass_data = FakeCar.create_fake_car(race_track,0.0075)
        ret = Receiver.Start(pass_data,race_track,self.display_func)
        assert(ret) # couldn't start receiver ??

    def stopCurrentRace(self):
        self.racePanel.appendOutput("You stopped the current race")
        ret = Receiver.Stop(10)
        if not ret:
            QtGui.QMessageBox.critical(self, "Receiver Error", "\nError - Could not stop receiver!\n\n")

    def raceMode(self):
        self.mainStack.setCurrentWidget(self.racePanel)

    def resultsMode(self):
        self.mainStack.setCurrentWidget(self.resultsPanel)

    def chartsMode(self):
        self.mainStack.setCurrentWidget(self.chartsPanel)

    def display_func(self, code, df):
        self.raceResult.emit(code, df)

    def getRaceResult(self, code="", df=None):
        if(code == "end"):
            self.startRace.setVisible(True)
            self.stopRace.setVisible(False)
